package client.libmessenger;

import java.net.*;
import common.*;

public class ConnectionsListener extends Thread
{	
	ServerSocket socket = null;
	int listeningPort = Constants.CLIENT_PORT;
	
	public ConnectionsListener()
	{
		super();
	}
	
	public ConnectionsListener(int listeningPort)
	{
		super();
		this.listeningPort = listeningPort;
	}
	
	public void run()
	{
		try
		{
			socket = new ServerSocket(this.listeningPort);
		} // TRY
		catch(Exception e)
		{
			System.out.println("While instantiating a server socket:");
			e.printStackTrace();
			System.exit(-1);
		}
		
		// start listening for connections
		while(!this.isInterrupted())
		{
			try
			{
				Socket clientSocket = socket.accept();
				System.out.println("Client connected from "+clientSocket.getRemoteSocketAddress().toString());								
				
				// start a new thread for that connection
				client.libmessenger.ClientThread thread = new ClientThread();
				thread.clientSocket = SocketWrapper.dup(clientSocket);
				new Thread(thread).start();								
			} // TRY
			catch(SocketTimeoutException e)
			{
				// do nothing, we can loop again and listen for further connections
			} // CATCH
			catch(Exception e)
			{
				if(!socket.isClosed())
				{
					// All other exceptions are deadly
					System.out.println("In ConnectionsListener::run(): While waiting for new connections:");
					e.printStackTrace();
					System.exit(-1);
				} // IF
			} // CATCH
		} // WHILE		
		
		try 
		{
			if (!socket.isClosed())
				socket.close();		
			//System.out.println("conslsd sserver socket dlcosed");
		} 
		catch(Exception e) 
		{
			System.out.println("In ConnectionsListener::run(): While closing:");
			e.printStackTrace();
			System.exit(-1);				
		}
	}

}
